import React, { useState } from 'react';
import { message } from 'antd';
import StockInvestmentPlanList, { SavedStockInvestmentPlan } from './components/StockInvestmentPlanList';
import StockInvestmentPlanForm from './components/StockInvestmentPlanForm';
import { stockPlanService, SavedStockPlan } from '../../services/stockPlanService';
import { 
  StockInfo, 
  InvestmentConfig, 
  InvestmentPlan as BaseInvestmentPlan, 
  StrategyType
} from '../../types/investment';
import './index.less';

interface InvestmentPlan extends BaseInvestmentPlan {
  stockInfo: StockInfo;
}

type ViewMode = 'list' | 'create' | 'edit' | 'view';

const StockInvestmentPlan: React.FC = () => {
  const [viewMode, setViewMode] = useState<ViewMode>('list');
  const [editingPlan, setEditingPlan] = useState<SavedStockInvestmentPlan | null>(null);

  // 切换到新增模式
  const handleCreateNew = () => {
    setEditingPlan(null);
    setViewMode('create');
  };

  // 切换到编辑模式
  const handleEdit = (plan: SavedStockInvestmentPlan) => {
    setEditingPlan(plan);
    setViewMode('edit');
  };

  // 查看投资计划详情
  const handleView = (plan: SavedStockInvestmentPlan) => {
    setEditingPlan(plan);
    setViewMode('view');
  };

  // 返回列表
  const handleBack = () => {
    setViewMode('list');
    setEditingPlan(null);
  };

  // 保存投资计划
  const handleSave = async (plan: InvestmentPlan) => {
    try {
      const savedPlan: SavedStockPlan = {
        id: editingPlan?.id || `stock_plan_${Date.now()}`,
        stockCode: plan.stockInfo.code,
        stockName: plan.stockInfo.name,
        stockType: plan.stockInfo.type,
        currentPrice: plan.stockInfo.currentPrice,
        maxDrawdown: plan.stockInfo.maxDrawdown,
        totalShares: plan.expectedShares,
        buyTimes: plan.buyPoints.length,
        strategy: 'pyramid',
        averagePrice: plan.averagePrice,
        riskLevel: plan.riskAnalysis.riskLevel,
        maxLoss: plan.riskAnalysis.maxLoss,
        totalAmount: plan.totalInvestment,
        minLots: 1,
        lotSize: 100,
        // trackingIndex: plan.stockInfo.,
        managementFee: 0.5,
        // createdAt: editingPlan?.createdAt || new Date().toISOString(),
        // updatedAt: new Date().toISOString()
      };

      if (editingPlan) {
        await stockPlanService.saveStockPlan(savedPlan);
        message.success('投资计划更新成功');
      } else {
        await stockPlanService.saveStockPlan(savedPlan);
        message.success('投资计划保存成功');
      }

      handleBack();
    } catch (error) {
      console.error('保存投资计划失败:', error);
      message.error('保存投资计划失败');
    }
  };

  // 删除投资计划
  const handleDelete = async (id: string) => {
    try {
      await stockPlanService.deleteStockPlan(id);
      message.success('投资计划删除成功');
    } catch (error) {
      console.error('删除投资计划失败:', error);
      message.error('删除投资计划失败');
    }
  };

  // 渲染不同的视图模式
  const renderContent = () => {
    switch (viewMode) {
      case 'list':
        return (
          <StockInvestmentPlanList
            onCreateNew={handleCreateNew}
            onEdit={handleEdit}
            onView={handleView}
            onDelete={handleDelete}
          />
        );
      case 'create':
        return (
          <StockInvestmentPlanForm
            mode="create"
            onSave={handleSave}
            onBack={handleBack}
          />
        );
      case 'edit':
        return (
          <StockInvestmentPlanForm
            mode="edit"
            initialPlan={editingPlan}
            onSave={handleSave}
            onBack={handleBack}
          />
        );
      case 'view':
        return (
          <StockInvestmentPlanForm
            mode="view"
            initialPlan={editingPlan}
            onBack={handleBack}
          />
        );
      default:
        return null;
    }
  };

  return (
    <div className="stock-investment-plan">
      {renderContent()}
    </div>
  );
};

export default StockInvestmentPlan;